package com.link.serve.tcp.handler.tactics.impl;


import com.link.serve.constants.ChannelAttrKey;
import com.link.serve.constants.LinkRedisKey;
import com.link.serve.tcp.linkdata.SingleUserChannelManager;
import com.link.serve.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 登录信息的断开处理类
 */
@Slf4j
@Component
public class LoginDisconnectionHandler {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 清除redis中的对应数据
     * @param ctx
     */
    public void handleDisconnection(ChannelHandlerContext ctx) {
        //从channel中获取用户id
        Long userId = (Long) ctx.channel().attr(AttributeKey.valueOf(ChannelAttrKey.USER_ID)).get();
        if (userId != null) {
//            RedisTemplate<String, Object> redisTemplate= SpringContextHolder.getBean("redisTemplate");
            String key = String.join(":", LinkRedisKey.LINK_USER_SERVER_ID, String.valueOf(userId));
            SingleUserChannelManager.removeChannel(userId);//删除map的连接

            //TODO:  通知用户

            log.info("断开用户{},总共心跳次数为{},当前存在人数{}",
                    userId,
                    ctx.channel().attr(AttributeKey.valueOf(ChannelAttrKey.HEARTBEAT_TIMES)).get(),
                    SingleUserChannelManager.getSize());
            redisTemplate.delete(key);
        }
    }
}